const { generateSheet } = require('../util')
Parse.Cloud.define('createQlOrder', async (req, res) => {
  const { productId, userId } = req.params
  try {
    const user = await new Parse.Query(Parse.User).equalTo('objectId', userId).first()
    if (!user) {
      return res.error('请先授权登录')
    }

    const product = await new Parse.Query('QlVip').equalTo('objectId', productId).first()
    if (!product) {
      return res.error('没有该商品')
    }

    const orderNo = generateSheet()
    const price = product.get('money')

    const order = new Parse.Object('QlOrder')
    const current = await order.save({
      product,
      user,
      price,
      status: 0,
      orderNo
    })

    const monthes = product.get('monthes')
    let unit = `${monthes}个月`

    if (monthes === 6) {
      unit = '半年'
    }
    if (monthes === 12) {
      unit = '1年'
    }

    res.success({
      id: current.id,
      price,
      orderNo,
      productId: product.id,
      unit
    })
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})
